﻿using Medianamik.Core.Cache;
using Medianamik.Core;
using Medianamik.Core.Interfaces;
using System.Collections.Generic;
using System.Linq;
using System;

namespace Medianamik.Core.Lock
{
    public class LockCacheManager : CacheManagerBase<LockCacheManager>, IEnumerable<ILock>
    {
        protected override string CacheKeyPrefix
        {
            get { return "LockCacheManager"; }
        }

        internal const string CACHEKEY_LOCKED_OBJECTS = "LockManager_AllLocks_LockInfo";
        /// <summary>
        /// List des Locks
        /// Cette collection est en cache
        /// </summary>
        public List<ILock> Locks
        {
            get
            {
                Func<List<ILock>> locks = () => (from l in DALProviderManager.DALProvider.ConfigDALProvider.GetLocks(1, int.MaxValue)
                                                 where l.IsAlive()
                                                 select l).ToList();
                return Get(CACHEKEY_LOCKED_OBJECTS, locks);
            }
        }

        public void Add(ILock pLock)
        {
            var lk = Locks.Find(l => l.LockId == pLock.LockId);
            if (lk != null) { Locks.Remove(lk); }
            Locks.Add(pLock);
        }

        public void Remove(ILock pLock)
        {
            var lk = Locks.Find(l => l.LockId == pLock.LockId);
            if (lk != null) { Locks.Remove(lk); }
        }

        public void Update(ILock pLock)
        {
            var lk = Locks.Find(l => l.LockId == pLock.LockId);
            if (lk != null) { Locks.Remove(lk); }
            Locks.Add(pLock);
        }

        #region IEnumerable<ILock> Members

        public IEnumerator<ILock> GetEnumerator()
        {
            return Locks.GetEnumerator();
        }

        #endregion

        #region IEnumerable Members

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return Locks.GetEnumerator();
        }

        #endregion
    }
}